package com.jyxd.web.controller.basic;

import com.jyxd.web.data.basic.BodyTemperature;
import com.jyxd.web.data.dto.ExtBodyTemplate;
import com.jyxd.web.data.log.Log;
import com.jyxd.web.data.patient.Patient;
import com.jyxd.web.data.user.User;
import com.jyxd.web.service.assessment.basic.BodyTemperatureService;
import com.jyxd.web.service.log.LogService;
import com.jyxd.web.service.patient.PatientService;
import com.jyxd.web.util.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Api(tags = "病人体温单相关接口")
@Controller
@RequestMapping(value = "/bodyTemperature")
public class BodyTemperatureController {

    private static Logger logger= LoggerFactory.getLogger(BodyTemperatureController.class);

    @Autowired
    private BodyTemperatureService bodyTemperatureService;

    @Autowired
    private LogService logService;

    @Autowired
    private PatientService patientService;

    /**
     * 增加一条体温单数据表记录
     * @return
     */
    @RequestMapping(value = "/insert")
    @ResponseBody
    public String insert(@RequestBody (required=false) Map<String,Object> map, HttpSession session){
        JSONObject json=new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("data",new ArrayList<>());
        json.put("msg","添加失败");
        try {
            JSONArray array=JSONArray.fromObject(map.get("list").toString());
            Map<String,Object> parameMap=new HashMap<>();
            SimpleDateFormat sdf =   new SimpleDateFormat( "yyyy-MM-dd HH:mm" );
            parameMap.put("dataTime",map.get("time").toString());
            if(array!=null && array.size()>0){
                for (int i = 0; i <array.size(); i++) {
                    JSONObject obj=(JSONObject) array.get(i);
                    parameMap.put("patientId",obj.getString("patientId"));
                    //口温
                    if(StringUtils.isNotEmpty(obj.getString("kouwen"))){
                        parameMap.put("code","口温");
                        //根据时间和code 查询 体温单对象
                        BodyTemperature bodyTemperature=bodyTemperatureService.queryDataByTimeAndCode(parameMap);
                        if(bodyTemperature!=null){
                            //不等于null 为编辑
                            bodyTemperature.setContent(obj.getString("kouwen"));
                            bodyTemperatureService.update(bodyTemperature);
                        }else{
                            //等于null 为新增
                            BodyTemperature data=newBodyTemperature(obj,session);
                            data.setCode("口温");
                            data.setContent(obj.getString("kouwen"));
                            bodyTemperatureService.insert(data);
                        }
                    }
                    //腋温
                    if(StringUtils.isNotEmpty(obj.getString("yewen"))){
                        parameMap.put("code","腋温");
                        //根据时间和code 查询 体温单对象
                        BodyTemperature bodyTemperature=bodyTemperatureService.queryDataByTimeAndCode(parameMap);
                        if(bodyTemperature!=null){
                            //不等于null 为编辑
                            bodyTemperature.setContent(obj.getString("yewen"));
                            bodyTemperatureService.update(bodyTemperature);
                        }else{
                            //等于null 为新增
                            BodyTemperature data=newBodyTemperature(obj,session);
                            data.setCode("腋温");
                            data.setContent(obj.getString("yewen"));
                            bodyTemperatureService.insert(data);
                        }
                    }
                    //肛温
                    if(StringUtils.isNotEmpty(obj.getString("gangwen"))){
                        parameMap.put("code","肛温");
                        //根据时间和code 查询 体温单对象
                        BodyTemperature bodyTemperature=bodyTemperatureService.queryDataByTimeAndCode(parameMap);
                        if(bodyTemperature!=null){
                            //不等于null 为编辑
                            bodyTemperature.setContent(obj.getString("gangwen"));
                            bodyTemperatureService.update(bodyTemperature);
                        }else{
                            //等于null 为新增
                            BodyTemperature data=newBodyTemperature(obj,session);
                            data.setCode("肛温");
                            data.setContent(obj.getString("gangwen"));
                            bodyTemperatureService.insert(data);
                        }
                    }
                    //脉搏
                    if(StringUtils.isNotEmpty(obj.getString("maibo"))){
                        parameMap.put("code","脉搏");
                        //根据时间和code 查询 体温单对象
                        BodyTemperature bodyTemperature=bodyTemperatureService.queryDataByTimeAndCode(parameMap);
                        if(bodyTemperature!=null){
                            //不等于null 为编辑
                            bodyTemperature.setContent(obj.getString("maibo"));
                            bodyTemperatureService.update(bodyTemperature);
                        }else{
                            //等于null 为新增
                            BodyTemperature data=newBodyTemperature(obj,session);
                            data.setCode("脉搏");
                            data.setContent(obj.getString("maibo"));
                            bodyTemperatureService.insert(data);
                        }
                    }
                    //心率
                    if(StringUtils.isNotEmpty(obj.getString("xinlv"))){
                        parameMap.put("code","心率");
                        //根据时间和code 查询 体温单对象
                        BodyTemperature bodyTemperature=bodyTemperatureService.queryDataByTimeAndCode(parameMap);
                        if(bodyTemperature!=null){
                            //不等于null 为编辑
                            bodyTemperature.setContent(obj.getString("xinlv"));
                            bodyTemperatureService.update(bodyTemperature);
                        }else{
                            //等于null 为新增
                            BodyTemperature data=newBodyTemperature(obj,session);
                            data.setCode("心率");
                            data.setContent(obj.getString("xinlv"));
                            bodyTemperatureService.insert(data);
                        }
                    }
                    //呼吸
                    if(StringUtils.isNotEmpty(obj.getString("huxi"))){
                        parameMap.put("code","呼吸");
                        //根据时间和code 查询 体温单对象
                        BodyTemperature bodyTemperature=bodyTemperatureService.queryDataByTimeAndCode(parameMap);
                        if(bodyTemperature!=null){
                            //不等于null 为编辑
                            bodyTemperature.setContent(obj.getString("huxi"));
                            bodyTemperatureService.update(bodyTemperature);
                        }else{
                            //等于null 为新增
                            BodyTemperature data=newBodyTemperature(obj,session);
                            data.setCode("呼吸");
                            data.setContent(obj.getString("huxi"));
                            bodyTemperatureService.insert(data);
                        }
                    }
                }
                User user=(User) session.getAttribute("user");
                if(user!=null){
                    //添加操作日志信息
                    Log log=new Log();
                    log.setId(UUIDUtil.getUUID());
                    log.setOperatorCode(user.getLoginName());
                    log.setOperateTime(new Date());
                    log.setMenuCode(MenuCode.TWDKJLR_CODE.getCode());
                    log.setContent(map.toString());
                    log.setOperateType(LogTypeCode.ADD_CODE.getCode());
                    log.setPatientId((String) parameMap.get("patientId"));
                    logService.insert(log);
                }
                json.put("code", HttpCode.OK_CODE.getCode());
                json.put("msg","添加成功");
            }
        }catch (Exception e){
            logger.info("增加一条体温单数据表记录:"+e.getMessage()+"  ------   "+e.toString()+"   "+e.getLocalizedMessage());
        }
        return json.toString();
    }

    public BodyTemperature newBodyTemperature(JSONObject jsonObject, HttpSession session){
        BodyTemperature bodyTemperature=new BodyTemperature();
        SimpleDateFormat sdf =   new SimpleDateFormat( "yyyy-MM-dd HH:mm" );
        try {
            bodyTemperature.setId(UUIDUtil.getUUID());
            bodyTemperature.setCreateTime(new Date());
            bodyTemperature.setStatus(1);
            bodyTemperature.setDataTime(sdf.parse(jsonObject.getString("dataTime")));
            bodyTemperature.setPatientId(jsonObject.getString("patientId"));
            bodyTemperature.setVisitCode(jsonObject.getString("visitCode"));
            bodyTemperature.setVisitId(jsonObject.getString("visitId"));
            User user =(User) session.getAttribute("user");
            if(user!=null){
                bodyTemperature.setOperatorCode(user.getLoginName());
            }
        }catch (Exception e){
            logger.info("newBodyTemperature:"+e);
        }
        return bodyTemperature;
    }

    /**
     * 更新体温单数据表记录状态
     * @param map
     * @return
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    public String update(@RequestBody(required=false) Map<String,Object> map){
        JSONObject json=new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("msg","更新失败");
        if(map!=null && map.containsKey("id") && map.containsKey("status") ){
            BodyTemperature bodyTemperature=bodyTemperatureService.queryData(map.get("id").toString());
            if(bodyTemperature!=null){
                bodyTemperature.setStatus((int)map.get("status"));
                bodyTemperatureService.update(bodyTemperature);
                json.put("msg","更新成功");
            }else{
                json.put("msg","更新失败，没有这个对象。");
                return json.toString();
            }
        }
        json.put("code", HttpCode.OK_CODE.getCode());
        return json.toString();
    }

    /**
     * 编辑体温单数据表记录单
     * @param map
     * @return
     */
    @RequestMapping(value = "/edit")
    @ResponseBody
    public String edit(@RequestBody(required=false) Map<String,Object> map){
        JSONObject json=new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("msg","编辑失败");
        if(map!=null && map.containsKey("id") && map.containsKey("status") && map.containsKey("bedName")){
            BodyTemperature bodyTemperature=bodyTemperatureService.queryData(map.get("id").toString());
            if(bodyTemperature!=null){
                bodyTemperature.setStatus((int)map.get("status"));
                bodyTemperatureService.update(bodyTemperature);
                json.put("msg","编辑成功");
            }else{
                json.put("msg","编辑失败，没有这个对象。");
                return json.toString();
            }
        }
        json.put("code", HttpCode.OK_CODE.getCode());

        return json.toString();
    }

    /**
     * 删除体温单数据表记录
     * @param map
     * @return
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public String delete(@RequestBody(required=false) Map<String,Object> map){
        JSONObject json=new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("msg","删除失败");
        if(map.containsKey("id")){
            BodyTemperature bodyTemperature=bodyTemperatureService.queryData(map.get("id").toString());
            if(bodyTemperature!=null){
                bodyTemperature.setStatus(-1);
                bodyTemperatureService.update(bodyTemperature);
                json.put("msg","删除成功");
            }else{
                json.put("msg","删除失败，没有这个对象。");
                return json.toString();
            }
        }
        json.put("code", HttpCode.OK_CODE.getCode());
        return json.toString();
    }

    /**
     * 根据主键id查询体温单数据表记录
     * @param map
     * @return
     */
    @RequestMapping(value = "/queryData",method= RequestMethod.POST)
    @ResponseBody
    public String queryData(@RequestBody(required=false) Map<String,Object> map){
        JSONObject json=new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("data",new ArrayList<>());
        json.put("msg","暂无数据");
        if(map !=null && map.containsKey("id")){
            BodyTemperature bodyTemperature=bodyTemperatureService.queryData(map.get("id").toString());
            if(bodyTemperature!=null){
                json.put("msg","查询成功");
                json.put("data",JSONObject.fromObject(bodyTemperature));
            }
        }
        json.put("code", HttpCode.OK_CODE.getCode());
        return json.toString();
    }

    /**
     * 根据条件分页查询体温单数据表记录列表（也可以不分页）
     * @param map
     * @return
     */
    @RequestMapping(value = "/queryList",method= RequestMethod.POST)
    @ResponseBody
    public String queryList(@RequestBody(required=false) Map<String,Object> map){
        JSONObject json=new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("data",new ArrayList<>());
        json.put("msg","暂无数据");
        if(map!=null && map.containsKey("start")){
            int totalCount =bodyTemperatureService.queryNum(map);
            map.put("start",((int)map.get("start")-1)*(int)map.get("size"));
            json.put("totalCount",totalCount);
        }
        List<BodyTemperature> list =bodyTemperatureService.queryList(map);
        if(list!=null && list.size()>0){
            json.put("msg","查询成功");
            json.put("data",JSONArray.fromObject(list));
        }
        json.put("code", HttpCode.OK_CODE.getCode());
        return json.toString();
    }

    /**
     * 根据时间查询在科病人的体温图数据
     * @param map
     * @return
     */
    @RequestMapping(value = "/getListByTime",method= RequestMethod.POST)
    @ResponseBody
    public String getListByTime(@RequestBody(required=false) Map<String,Object> map){
        JSONObject json=new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("data",new ArrayList<>());
        json.put("msg","暂无数据");
        List<Map<String,Object>> list=bodyTemperatureService.getListByTime(map);
        if(list!=null && list.size()>0){
            JsonConfig jsonConfig=new JsonConfig();
            jsonConfig.registerJsonValueProcessor(Timestamp.class,new JsonArrayValueProcessor());
            JSONArray array=JSONArray.fromObject(list,jsonConfig);
            json.put("data",array);
            json.put("code", HttpCode.OK_CODE.getCode());
            json.put("msg","查询成功");
        }
        return json.toString();
    }


    /**
     * 根据时间，病人id查询在科病人的体温数据
     * @param map
     * @return
     */
    @RequestMapping(value = "/queryDataByTimeAndPatientId",method= RequestMethod.POST)
    @ResponseBody
    public String queryDataByTimeAndPatientId(@RequestBody(required=false) Map<String,Object> map){
        JSONObject json=new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("data",new ArrayList<>());
        json.put("msg","暂无数据");
        List<ExtBodyTemplate> list=bodyTemperatureService.queryDataByTimeAndPatientId(map);
        map.remove("start");
        map.remove("size");
        //List<Map<String,Object>> sumlist=bodyTemperatureService.queryDataByTimeAndPatientId(map);
        //json.put("totalCount",sumlist.size());
        json.put("data",JSONArray.fromObject(list));
        json.put("code", HttpCode.OK_CODE.getCode());
        json.put("msg","查询成功");
        return json.toString();
    }


    /**
     * 保存体温单数据表记录
     * @return
     */
    @ApiOperation("添加修改体温表记录")
    @RequestMapping(value = "/saveData", method = RequestMethod.POST)
    @ResponseBody
    public String saveData(@RequestBody (required=false) Map<String,Object> map, HttpSession session){
        JSONObject json=new JSONObject();
        json.put("code", HttpCode.FAILURE_CODE.getCode());
        json.put("data",new ArrayList<>());
        json.put("msg","保存失败");
        try {
            JSONObject jsonObject = JSONObject.fromObject(map.get("body"));
            JSONArray array=JSONArray.fromObject(jsonObject.get("list"));
            Map<String,Object> parameMap=new HashMap<>();
            parameMap.put("patientId",jsonObject.get("patientId").toString());
            parameMap.put("dataTime",jsonObject.get("dataTime").toString().substring(0, 10));
            String  row_Id= UUIDUtil.getUUID();
            bodyTemperatureService.deleteByPatientIdAndNowTime(parameMap);
            if(array!=null && array.size()>0){
                for (int i = 0; i <array.size(); i++) {
                    JSONObject obj=(JSONObject) array.get(i);
                    String rowId = obj.getString("id");
                    boolean flag=insertRow(obj,session,jsonObject,rowId);
                    if(flag){
                        json.put("msg", "保存成功");
                        json.put("code", HttpCode.OK_CODE.getCode());
                    }else {
                        json.put("code", HttpCode.FAILURE_CODE.getCode());
                        json.put("msg", "保存失败");
                    }

                }

            }
        }catch (Exception e){
            json.put("msg","保存失败");
            logger.info("增加一条体温单数据表记录:"+e.getMessage()+"  ------   "+e.toString()+"   "+e.getLocalizedMessage());
        }
        return json.toString();
    }
    public boolean insertRow(JSONObject obj,HttpSession session,JSONObject jsonObject,String rowId){
        boolean  flag =true;
        try {
            BodyTemperature bodyTemperature = newBody(jsonObject, session);
            try {
                bodyTemperature.setDataTime(DateUtil.yyyyMMddHHmmSdfToDate(jsonObject.get("dataTime").toString().substring(0, 10) + " " + obj.getString("dateHour")));
            } catch (ParseException e) {
                e.printStackTrace();
            }
            bodyTemperature.setRowId(rowId);
            bodyTemperature.setCode("口温");
            bodyTemperature.setContent(obj.get("mouthTemplate").toString());
            bodyTemperatureService.insert(bodyTemperature);
            BodyTemperature bodyTemperature2 = newBody(jsonObject, session);
            try {

                bodyTemperature2.setDataTime(DateUtil.yyyyMMddHHmmSdfToDate(jsonObject.get("dataTime").toString().substring(0, 10) + " " + obj.getString("dateHour")));
            } catch (ParseException e) {
                e.printStackTrace();
            }
            bodyTemperature2.setRowId(rowId);
            bodyTemperature2.setCode("腋温");
            bodyTemperature2.setContent(obj.get("armpitTemplate").toString());

            bodyTemperatureService.insert(bodyTemperature2);
            BodyTemperature bodyTemperature3 = newBody(jsonObject, session);
            try {

                bodyTemperature3.setDataTime(DateUtil.yyyyMMddHHmmSdfToDate(jsonObject.get("dataTime").toString().substring(0, 10) + " " + obj.getString("dateHour") + ":00"));
            } catch (ParseException e) {
                e.printStackTrace();
            }
            bodyTemperature3.setRowId(rowId);
            bodyTemperature3.setCode("肛温");
            bodyTemperature3.setContent(obj.get("anusTemplate").toString());
            bodyTemperatureService.insert(bodyTemperature3);
        }
        catch (Exception e){
            flag=false;
            logger.info("增加一条体温单数据表记录:"+e.getMessage()+"  ------   "+e.toString()+"   "+e.getLocalizedMessage());
        }
        return flag;
    }

    public BodyTemperature newBody(JSONObject obj, HttpSession session){
        User user=(User) session.getAttribute("user");
        BodyTemperature bodyTemperature = new BodyTemperature();
        bodyTemperature.setId(UUIDUtil.getUUID());
        bodyTemperature.setVisitId(obj.get("visitId").toString());
        bodyTemperature.setVisitCode(obj.get("visitCode").toString());
        bodyTemperature.setPatientId(obj.get("patientId").toString());
        bodyTemperature.setCreateTime(new Date());
        bodyTemperature.setOperatorCode(user.getLoginName());
        bodyTemperature.setStatus(1);
        return bodyTemperature;
    }

    /**
     * 根据患者id查询当前时间体温表相关数据
     * @param map
     * @return
     */
    @RequestMapping(value = "/getDataByPatientId",method= RequestMethod.POST)
    @ResponseBody
    public String getDataByPatientId(@RequestBody(required=false) Map<String,Object> map){
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            JSONObject json=new JSONObject();
            json.put("code",HttpCode.FAILURE_CODE.getCode());
            json.put("data",new ArrayList<>());
            json.put("msg","暂无数据");
            //通过病人id查询到病人的信息
            Patient patient = patientService.queryData(map.get("PatientId").toString());
            Date nowtime = new Date();
            Date entertime = patient.getVisitTime();
            //Date entertime = patient.getEnterTime();
            String enterTime = DateUtil.yyyyMMddSdfToString(entertime);
            //判断当前时间是否大于出科时间，如果大于出科时间，赋值出科时间
            Date exitTime= patient.getExitTime();
            String nowTime = DateUtil.yyyyMMddSdfToString(nowtime);
            if(exitTime!=null && !"".equals(exitTime)){
                String exitTimeStr = DateUtil.yyyyMMddSdfToString(exitTime);
                if(nowTime.compareTo(exitTimeStr)>=0){
                    nowTime=exitTimeStr;
                }
            }
            try {
                int inHospitalDays = between_days(enterTime, nowTime).intValue()+1;//住院天数
                int week= inHospitalDays/7;
                int remainder = inHospitalDays%7;
                if (remainder>0){
                    week++;
                }
                List<String> dateList = new ArrayList<>();
                List<Integer> days = new ArrayList<Integer>();
                switch (remainder){
                    case 0: //余数为0，说明是第week周的第七天
                        dateList = getNDaysList("", nowTime, 7);
                        days.add(inHospitalDays-6);
                        days.add(inHospitalDays-5);
                        days.add(inHospitalDays-4);
                        days.add(inHospitalDays-3);
                        days.add(inHospitalDays-2);
                        days.add(inHospitalDays-1);
                        days.add(inHospitalDays);
                        break;
                    case 1:
                        dateList = getNDaysList(nowTime, "", 7);
                        days.add(inHospitalDays);
                        days.add(inHospitalDays+1);
                        days.add(inHospitalDays+2);
                        days.add(inHospitalDays+3);
                        days.add(inHospitalDays+4);
                        days.add(inHospitalDays+5);
                        days.add(inHospitalDays+6);
                        break;
                    case 2:
                        dateList = getNDaysList("",nowTime,2);
                        dateList.addAll(getNDaysList(nowTime, "", 6));
                        days.add(inHospitalDays-1);
                        days.add(inHospitalDays);
                        days.add(inHospitalDays+1);
                        days.add(inHospitalDays+2);
                        days.add(inHospitalDays+3);
                        days.add(inHospitalDays+4);
                        days.add(inHospitalDays+5);
                        break;
                    case 3:
                        dateList = getNDaysList("", nowTime, 3);
                        dateList.addAll(getNDaysList(nowTime, "", 5));
                        days.add(inHospitalDays-2);
                        days.add(inHospitalDays-1);
                        days.add(inHospitalDays);
                        days.add(inHospitalDays+1);
                        days.add(inHospitalDays+2);
                        days.add(inHospitalDays+3);
                        days.add(inHospitalDays+4);
                        break;
                    case 4:
                        dateList = getNDaysList("", nowTime, 4);
                        dateList.addAll(getNDaysList(nowTime, "", 4));
                        days.add(inHospitalDays-3);
                        days.add(inHospitalDays-2);
                        days.add(inHospitalDays-1);
                        days.add(inHospitalDays);
                        days.add(inHospitalDays+1);
                        days.add(inHospitalDays+2);
                        days.add(inHospitalDays+3);
                        break;
                    case 5:
                        dateList = getNDaysList("", nowTime, 5);
                        dateList.addAll(getNDaysList(nowTime, "", 3));
                        days.add(inHospitalDays-4);
                        days.add(inHospitalDays-3);
                        days.add(inHospitalDays-2);
                        days.add(inHospitalDays-1);
                        days.add(inHospitalDays);
                        days.add(inHospitalDays+1);
                        days.add(inHospitalDays+2);
                        break;
                    case 6:
                        dateList = getNDaysList("", nowTime, 6);
                        dateList.addAll(getNDaysList(nowTime, "", 2));
                        days.add(inHospitalDays-5);
                        days.add(inHospitalDays-4);
                        days.add(inHospitalDays-3);
                        days.add(inHospitalDays-2);
                        days.add(inHospitalDays-1);
                        days.add(inHospitalDays);
                        days.add(inHospitalDays+1);
                        break;
                }
                List<String> listNew = new ArrayList<String>(new TreeSet<String>(dateList));
                Map<String,Object> selectmap = new HashMap();
                selectmap.put("patientId",map.get("PatientId").toString());
                selectmap.put("startTime",listNew.get(0));
                selectmap.put("endTime",listNew.get(listNew.size()-1));
                //查询口温
                /**
                 List<ExtBodyTemplate> AnusTemplateList = bodyTemperatureService.getListByWeekAnusTemplate(selectmap);
                 List<ExtBodyTemplate> MouthTemplateList = bodyTemperatureService.getListByWeekMouthTemplate(selectmap);
                 List<ExtBodyTemplate> ArmpitTemplateList = bodyTemperatureService.getListByWeekArmpitTemplate(selectmap);
                 **/
                Map<String, Object> data = new HashMap<String, Object>();

                bodyTemperatureService.getAllList(listNew,map.get("PatientId").toString(),data,week);
                data.put("hospitalDays",days);
                data.put("week",week);
                data.put("dayList",listNew);
                json.put("code",HttpCode.OK_CODE.getCode());
                json.put("msg","查询成功");
                json.put("data",data);
            }catch (Exception e) {
                e.printStackTrace();
            }
            return json.toString();
    }

    /**
     * 根据患者id与第几周查询体温表相关数据
     * @param map
     * @return
     */
    @RequestMapping(value = "/getDataByPatientIdAndWeek",method= RequestMethod.POST)
    @ResponseBody
    public String getDataByPatientIdAndWeek(@RequestBody(required=false) Map<String,Object> map){
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        JSONObject json=new JSONObject();
        json.put("code",HttpCode.FAILURE_CODE.getCode());
        json.put("data",new ArrayList<>());
        json.put("msg","暂无数据");
        //通过病人id查询到病人的信息
        Patient patient = patientService.queryData(map.get("PatientId").toString());
        Date entertime = patient.getVisitTime();
        try {
            int weeknum =Integer.valueOf(map.get("week").toString());//第几周
            //判断当前时间是否大于出科时间，如果大于出科时间，赋值出科时间
            Date exitTime= patient.getExitTime();
            String nowTime ="";
            if(exitTime!=null && !"".equals(exitTime)){
                String exitTimeStr = DateUtil.yyyyMMddSdfToString(exitTime);
                String entertimeStr = DateUtil.yyyyMMddSdfToString(entertime);
                int inHospitalDays = between_days(entertimeStr, exitTimeStr).intValue()+1;//住院天数
                int week= inHospitalDays/7;
                int remainder = inHospitalDays%7;
                if (remainder>0){
                    week++;
                }
                if(weeknum>week){
                    weeknum=week;
                }
            }


            //先取出最后的日期
            String firstDate = getDateAfter(entertime,weeknum*7-7);;
            String endDate = getDateAfter(entertime,weeknum*7-1);
            List<String> dateList= SliceUpDateUtil.sliceUpDateRange(firstDate,endDate,3);
            List<Integer> hospitalDays=new LinkedList<Integer>();
            hospitalDays.add(weeknum*7-6);
            hospitalDays.add(weeknum*7-5);
            hospitalDays.add(weeknum*7-4);
            hospitalDays.add(weeknum*7-3);
            hospitalDays.add(weeknum*7-2);
            hospitalDays.add(weeknum*7-1);
            hospitalDays.add(weeknum*7);
            Map<String,Object> data = new HashMap();
            bodyTemperatureService.getAllList(dateList,map.get("PatientId").toString(),data,weeknum);
            /**
             List<ExtBodyTemplate> AnusTemplateList = bodyTemperatureService.getListByWeekAnusTemplate(selectmap);
             List<ExtBodyTemplate> MouthTemplateList = bodyTemperatureService.getListByWeekMouthTemplate(selectmap);
             List<ExtBodyTemplate> ArmpitTemplateList = bodyTemperatureService.getListByWeekArmpitTemplate(selectmap);
             **/
            data.put("hospitalDays",hospitalDays);
            data.put("week",weeknum);
            data.put("dayList",dateList);
            json.put("data",data);
            json.put("code",HttpCode.OK_CODE.getCode());
            json.put("msg","查询成功");
        }catch (Exception e) {
            e.printStackTrace();
        }
        return json.toString();
    }


    public static Long between_days(String a, String b) {

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");// 自定义时间格式

        Calendar calendar_a = Calendar.getInstance();// 获取日历对象
        Calendar calendar_b = Calendar.getInstance();

        Date date_a = null;
        Date date_b = null;

        try {
            date_a = simpleDateFormat.parse(a);//字符串转Date
            date_b = simpleDateFormat.parse(b);
            calendar_a.setTime(date_a);// 设置日历
            calendar_b.setTime(date_b);
        } catch (ParseException e) {
            e.printStackTrace();//格式化异常
        }

        long time_a = calendar_a.getTimeInMillis();
        long time_b = calendar_b.getTimeInMillis();

        long between_days = (time_b - time_a) / (1000 * 3600 * 24);//计算相差天数

        return between_days;
    }

    /**
     *  用户可以传入startTime或endTime任意一个或两个，也可以不传入
     *  当传入的时间间隔太长时，默认返回最近的nday
     *  plus: StringUtils为org.apache.commons.lang.StringUtils，读者也可以手动判断""和null
     */
    public List<String> getNDaysList(String startTime, String endTime, int nday) {
        int ndaycurrent = nday - 1;
        // 返回的日期集合
        List<String> days = new ArrayList<String>();
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.DATE,-ndaycurrent);
            Date start = calendar.getTime();
            Date end = new Date();
            if (StringUtils.isNotBlank(startTime) && StringUtils.isBlank(endTime)){
                //如果用户只选择了startTime,endTime为null,startTime + 10的日期
                start = dateFormat.parse(startTime);
                Calendar calendar1 = Calendar.getInstance();
                calendar1.setTime(start);
                calendar1.add(Calendar.DATE, ndaycurrent);
                end = calendar1.getTime();
            }else if(StringUtils.isBlank(startTime) && StringUtils.isNotBlank(endTime)){
                //如果用户只选择了endTime,startTime为null,endTime - 10的日期
                end = dateFormat.parse(endTime);
                Calendar calendar2 = Calendar.getInstance();
                calendar2.setTime(end);
                calendar2.add(Calendar.DATE, -ndaycurrent);
                start = calendar2.getTime();
            }else if (StringUtils.isNotBlank(startTime) && StringUtils.isNotBlank(endTime)){
                //如果用户选择了startTime和endTime，判断endTime - startTime两个日期是否超过了ndaycurrent，超过返回最近nday天记录
                Date start1 = dateFormat.parse(startTime);
                Date end1 = dateFormat.parse(endTime);
                int a = (int) ((end1.getTime() - start1.getTime()) / (1000*3600*24));
                if (a <= ndaycurrent) {
                    //如果小于等于n天
                    start = dateFormat.parse(startTime);
                    end = dateFormat.parse(endTime);
                }
            }
            //如果超过了ndaycurrent天,就是默认的start和end
            Calendar tempStart = Calendar.getInstance();
            tempStart.setTime(start);

            Calendar tempEnd = Calendar.getInstance();
            tempEnd.setTime(end);
            tempEnd.add(Calendar.DATE, +1);// 日期加1(包含结束)

            while (tempStart.before(tempEnd)) {
                days.add(dateFormat.format(tempStart.getTime()));
                tempStart.add(Calendar.DAY_OF_YEAR, 1);
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return days;
    }

    /**
     * 获取当前日期前(后)x天的日期
     *
     * @param day
     *            天数（如果day数为负数,说明是此日期前的天数）
     * @param sdf 日期格式
     */
    public static String getBeforNumDay(SimpleDateFormat sdf,int day) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.DATE, day);
        return sdf.format(calendar.getTime());
    }

    /**
     * 获取几天后的时间
     * @param d
     * @param day
     * @return
     */
    public static String getDateAfter(Date d, int day) {
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Calendar now = Calendar.getInstance();
        now.setTime(d);
        now.set(Calendar.DATE, now.get(Calendar.DATE) + day);
        return dateFormat.format(now.getTime());
    }

}
